// router.js
// 路由配置

// 创建路由实例
const { createRouter, createWebHashHistory } = VueRouter;
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        // 登录相关
        { path: '/', redirect: '/login' },
        { path: '/login', component: 'Login' },
        { path: '/login/counselor', component: 'CounselorLogin' },
        { path: '/login/student', component: 'StudentLogin' },

        // 辅导员模块
        {
            path: '/counselor',
            component: 'CounselorHome',
            meta: { requiresAuth: true, role: 'COUNSELOR' }
        },
        {
            path: '/counselor/holidays',
            component: 'HolidayPublish',
            meta: { requiresAuth: true, role: 'COUNSELOR' }
        },
        {
            path: '/counselor/report',
            component: 'Report',
            meta: { requiresAuth: true, role: 'COUNSELOR' }
        },

        // 学生模块
        {
            path: '/student',
            component: 'StudentHome',
            meta: { requiresAuth: true, role: 'STUDENT' }
        },
        {
            path: '/student/travel',
            component: 'TravelQuery',
            meta: { requiresAuth: true, role: 'STUDENT' }
        },
        {
            path: '/student/record-form',
            component: 'RecordForm',
            meta: { requiresAuth: true, role: 'STUDENT' }
        }
    ]
});

// 全局前置守卫（权限控制）
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token');
    const userRole = localStorage.getItem('role');

    // 需要认证的路由
    if (to.meta.requiresAuth) {
        if (!token) {
            next('/login');
        } else if (to.meta.role && to.meta.role !== userRole) {
            // 角色不匹配
            if (userRole === 'COUNSELOR') {
                next('/counselor');
            } else if (userRole === 'STUDENT') {
                next('/student');
            } else {
                next('/login');
            }
        } else {
            next();
        }
    }
    // 不需要认证的路由
    else {
        if (token && to.path === '/login') {
            // 已登录，跳转到首页
            if (userRole === 'COUNSELOR') {
                next('/counselor');
            } else if (userRole === 'STUDENT') {
                next('/student');
            } else {
                next();
            }
        } else {
            next();
        }
    }
});

// 将路由实例挂载到Vue应用
const app = Vue.createApp({});
app.use(router);
